<template>
  <div class="app-container" id="container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="70px"
             class="top-input">
<!--      <el-form-item label="区域名称" prop="fenceName" >-->
<!--        <el-input-->
<!--          v-model="queryParams.districtName"-->
<!--          placeholder="请输区域名称"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item prop="cityCode" label="城市">
        <el-select v-model="queryParams.cityCode" placeholder="请选择城市" @change="getDistrict">
          <el-option
            v-for="dict in cityOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="行政区" prop="adcode">
        <el-select v-model="queryParams.adcode" placeholder="请选择行政区">
          <el-option
            v-for="district in districtOptions"
            :key="district.adcode"
            :label="district.name"
            :value="district.adcode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="乡镇属性" prop="districtPop" v-if="(userPop.length == 2)">
        <el-select v-model="queryParams.districtPop" placeholder="请选择行政区" >
          <el-option
            v-for="district in userPopOptions"
            :key="district.dictValue"
            :label="district.dictLabel"
            :value="parseInt(district.dictValue)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery(0)">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8 top-btn">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleOpenAdd"
          v-if="!isAddStatus"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-save"
          size="mini"
          v-if="isAddStatus"
          @click="handleSave"
        >保存</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-save"
          size="mini"
          v-if="isAddStatus"
          @click="handleResetDraw"
        >重新绘制</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          v-if="isEndEdit"
          icon="el-icon-save"
          size="mini"
          @click="isEdit(1)"
        >结束落点</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          v-if="isAddStatus"
          @click="handleClose"
        >退出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          v-if="this.userPop[0] === 1"
          @click="copyTown"
        >复制区域</el-button>
      </el-col>
    </el-row>

    <div id="district">
      <!-- 复制对话框 -->
      <el-dialog :title="title" :visible.sync="openCopy" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="城市" prop="cityCode" >
            <el-select v-model="form.cityCode" placeholder="请选择城市" @change="getLocalDistrict">
              <el-option
                v-for="dict in cityOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区县" prop="parentId">
            <el-select v-model="form.parentId" placeholder="请选择区县" @change="getLocalTowns">
              <el-option
                v-for="district in localDistrictOptions"
                :key="district.id"
                :label="district.districtName"
                :value="district.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="乡镇" >
            <el-select v-model="form.town" clearable placeholder="请选择乡镇" @change="checkIsCopy">
              <el-option
                v-for="district in townsDistrictOptions"
                :key="district.id"
                :label="district.districtName"
                :value="district.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleCopyDistrict" >确定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 新增对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item  label="区域名称" prop="districtName" >
            <el-input v-model="form.districtName" placeholder="请输入围栏名称" style="width: 80%"/>
          </el-form-item>
          <el-form-item label="城市" prop="cityCode" >
            <el-select v-model="form.cityCode" placeholder="请选择城市" @change="getLocalDistrict">
              <el-option
                v-for="dict in cityOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区县" prop="parentId">
            <el-select v-model="form.parentId" placeholder="请选择区县" @change="getTowns">
              <el-option
                v-for="district in localDistrictOptions"
                :key="district.id"
                :label="district.districtName"
                :value="district.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="乡镇" prop="town" v-if="assistTools">
            <el-select v-model="form.town" placeholder="请选择乡镇" >
              <el-option
                v-for="district in townsDistrictOptions"
                :key="district.center"
                :label="district.name"
                :value="district.center"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="乡镇属性" prop="districtPop" v-if="userPop.length == 2" >
            <el-select v-model="form.districtPop" placeholder="请选择乡镇" @change="isEqualPop" >
              <el-option
                v-for="district in userPopOptions"
                :key="district.dictValue"
                :label="district.dictLabel"
                :value="parseInt(district.dictValue)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-switch
              active-text="是否启用乡镇辅助工具"
              v-model="assistTools"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleAddDistrict">确定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog :title="title" :visible.sync="modifyName" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item  label="乡镇名称" prop="districtName" >
            <el-input v-model="form.districtName" placeholder="请输入围栏名称" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleUpdateName(1)">确定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<style>
  html, body, #container {
    width: 100%;
    margin: 0;
  }

  .top-btn {
    position: fixed;
    margin-bottom: 7px;
    z-index: 999;
    top: 150px;
  }
  .top-input {
    position: fixed;
    margin-bottom: 7px;
    z-index: 999;
  }
</style>
<script>
  import AMapLoader from '@amap/amap-jsapi-loader';
  import $ from 'jquery';
  import {
    listDistrict,
    checkDistrict,
    saveQyCache,
    genQyPoints,
    getDistrictByCity,
    getLocalDistrictByCity,
    delDistrict,
    resetTownDistrict,
    getTowsPopByRole,
    resetDistrict,
    copyTownOrDistrict,
    checkIsCopy
  } from "@/api/integration/district";
  import log from "@/views/monitor/test/log";

  var map;
  var mouseTool;
  var polyEditor;
  var contextMenu;
  var contextQYMenu;
  var opType;
  var circleEditor;
  var circle;
  var tempDistrict = {};
  var rightClickPolygon;
  var districtPolygons= [];
  var districtPolygon = null;
  var infoWindow;
  var geocoder
  var circleMarker;
  export default {
    name: "District",
    components: {},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 显示搜索条件
        showSearch: true,
        // 弹出层标题
        title: "",
        townsList: [],
        districtList: [],
        cityOptions: [],
        localDistrictOptions: [],
        districtOptions: [],
        townsDistrictOptions: [],
        userPopOptions: [],
        // 是否显示弹出层
        open: false,
        openCopy: false,
        modifyName: false,
        // 是否使用辅助工具
        assistTools: false,
        userPop: [],
        // 是否结束编辑圆
        isEndEdit: false,
        // 是否为新增状态
        isAddStatus: false,
        // 查询参数
        queryParams: {
          // cityCode : '0791'
        },
        // 围栏表单参数
        form: {

        },
        // 表单校验
        rules: {
          cityCode: [
            {required: true, message: "请选择城市", trigger: "blur"}
          ],
          parentId: [
            {required: true, message: "请选择区县", trigger: "blur"}
          ],
          districtName: [
            {required: true, message: "请输入区域名称", trigger: "blur"}
          ],
          town: [
            {required: true, message: "请选择乡镇", trigger: "blur"}
          ],
          districtPop: [
            {required: true, message: "请选择乡镇属性", trigger: "blur"}
          ],
        }
      };
    },
    created() {
      getTowsPopByRole().then(response => {
        this.userPop = response.data;
      }).then(() => {
        this.init();
      })
      this.getDicts("city").then(response => {
        this.cityOptions = response.data;
      });
      this.getDicts("district_type").then(response =>{
        this.userPopOptions = response.data;
      })
    },
    methods: {
      init() {
        AMapLoader.load({
          "key": "3fa060bd1711d61ee47bb8983d7b1101",              // 申请好的Web端开发者Key，首次调用 load 时必填
          "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          "plugins": ['AMap.Scale', 'AMap.ToolBar', 'AMap.PolygonEditor','AMap.CircleEditor','AMap.MouseTool','AMap.CircleMarker',"AMap.GeometryUtil","AMap.PlaceSearch", "AMap.AutoComplete" ,"AMap.Geocoder"],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        }).then((AMap) => {
          map = new AMap.Map('container', {
            resizeEnable: true,
            /*center: [116.471354, 39.994257],*/
            zoom: 8,
            showIndoorMap: false
          });
        infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
        map.addControl(new AMap.Scale())
        map.addControl(new AMap.ToolBar())
        mouseTool = new AMap.MouseTool(map);
        contextMenu = new AMap.ContextMenu();
        contextMenu.addItem("修改名称", this.handleUpdateName, 0);
        contextMenu.addItem("修改坐标", this.handleUpdate, 1);
        // contextMenu.addItem("删除", this.handleDelete, 2);
        contextMenu.addItem("重置乡镇", this.handleReset, 3);
        polyEditor = new AMap.PolygonEditor(map);
        polyEditor.on('add', this.addCache);
        polyEditor.on('end', this.updateCache)
        this.getDistrictList()
        this.getList();
        $("#container").css("height", (document.body.offsetHeight) - 85 + "px")
      }).catch(e => {
          console.log(e);
      })
      },
      initPolygon(district) {
        var str = district.ydistrictPoints.split(";");
        var path = [];
        for (var i = 0; i < str.length; i++) {
          var point = str[i].split(",");
          var zb = new AMap.LngLat(point[0], point[1])
          path.push(zb);
        }
        var polygon = new AMap.Polygon({
          path: path,
          fillColor: district.districtColor,
          strokeOpacity: 1,
          fillOpacity: 0.5,
          strokeColor: '#2b8cbe',
          extData: {
            district: district
          }
        });
        polygon.content = '乡镇名称：' + district.districtName;
        map.add(polygon);
        polygon.on('click', this.polygonClick);
        polygon.on('rightclick', function (e) {
          rightClickPolygon = e.target;
          contextMenu.open(map, e.lnglat);
          infoWindow.close();
        });

      },
      polygonClick(e) {
        infoWindow.setContent(e.target.content);
        infoWindow.open(map, e.lnglat);
        contextMenu.close();
        contextQYMenu.close();
      },
      initQyPolygon(qy) {
        if(qy.districtPoints!=""){
          var str = qy.districtPoints.split(";");
          var path = [];
          for(var i=0;i<str.length;i++) {
            var point = str[i].split(",");
            var zb = new AMap.LngLat(point[0], point[1])
            path.push(zb);
          }
          //查询可分配围栏的区域坐标
          var polygon = new AMap.Polygon({
            path: path,
            fillColor: '#ccebc5',
            strokeOpacity: 1,
            fillOpacity: 0.5,
            strokeColor: '#2b8cbe',
            strokeWeight: 1,
            strokeStyle: 'dashed',
            strokeDasharray: [5, 5],
            extData: {
              districtId: qy.id,
              district: qy
            }
          });
          if(opType === "query"){
            map.setFitView(
              polygon,  // 覆盖物数组
              false,  // 动画过渡到制定位置
              [60, 60, 60, 60],  // 周围边距，上、下、左、右
              14,  // 最大 zoom 级别
            );
          }
          polygon.content = '区县名称：'+qy.districtName;
          contextQYMenu = new AMap.ContextMenu();
          contextQYMenu.addItem("重置区县", this.handleReset, 0);
          polygon.on('rightclick', this.rightClickReset)
          map.add(polygon);
          polygon.on('click', this.genCircleMarker);
          districtPolygons.push(polygon);
        }
      },
      // 区县右键重置
      rightClickReset(e){
        if(!this.isAddStatus){
          rightClickPolygon = e.target;
          contextQYMenu.open(map, e.lnglat);
        }
      },
      genCircleMarker(e){
        infoWindow.close();
        contextQYMenu.close();
        contextMenu.close();
        if( this.isEndEdit === true && this.isEditPoint === true){
          var marker = new AMap.Marker({
            position: e.lnglat,
          });
          map.add(marker);
          marker.on('rightclick' ,this.delCircleMarker);
        }
      },
      delCircleMarker(e){
        map.remove(e.target);
      },
      //查询初始化区域
      getDistrictList(){
        map.remove(districtPolygons);
        districtPolygons = [];
        this.queryParams.districtLevel = 2;
        listDistrict(this.queryParams).then(response => {
          this.districtList = response.data;
          for(var i=0;i<this.districtList.length;i++){
            var table = this.districtList[i];
            this.initQyPolygon(table);
          }
          opType = "";
        });

      },
      getList() {
        this.queryParams.districtLevel = 3;
        listDistrict(this.queryParams).then(response => {
          this.townsList = response.data;
          for (var i = 0; i < this.townsList.length; i++) {
            var table = this.townsList[i];
            this.initPolygon(table);
          }
        });
      },
      updateCache(data){
        var polygon = data.target;
        if(opType=="reset"){
          map.remove(polygon);
        }
        if(opType == "saveCache"){
          //将地图页面上的围栏保存到数据库中
          if(polygon==null){
            this.msgError("无数据可以保存");
            return;
          }
          var path = polygon.getPath();
          //检查围栏坐标点的移入动作是否移入到了其他围栏中移入了则将2边界重合
          var points = "";
          for(var i=0;i<path.length;i++){
            if (i < path.length - 1) {
              points = points+path[i].getLng()+","+path[i].getLat()+";"
            } else {
              points = points+path[i].getLng()+","+path[i].getLat();
            }
          }
          tempDistrict.districtPoints = points;
          tempDistrict.pointList = path;
          tempDistrict.ydistrictPoints = points;
          if(districtPolygon!=null){
            tempDistrict.districtPointList = districtPolygon.getPath();
          }
          if(this.form.districtPop == null){
            tempDistrict.districtPop = this.userPop[0];
          }
          saveQyCache(tempDistrict).then(response => {
            if (response.data.code == 200) {
              this.handleQuery();
              this.reset();
              this.msgSuccess("保存成功");
            } else {
              polyEditor.setTarget(polygon);
              polyEditor.open();
              this.$message({
                showClose: true,
                message: "警告:" + response.data.message,
                type: 'warning'
              });
            }
            opType = "";
        });
        }
      },
      /** 判断所选的乡镇属性是否和地图相同 */
      isEqualPop(value){
        if(this.queryParams.districtPop === undefined){
          this.msgError("请搜索相同乡镇属性地图")
        }else if(this.queryParams.districtPop !== undefined){
          if(this.queryParams.districtPop === value){
            this.isConfirm = false;
          }else {
            this.msgError("请搜索相同乡镇属性地图")
          }
        }
      },
      //切割区域生成围栏坐标
      addCache(data){
        //当前围栏对象
        var polygon = data.target;
        //当前围栏坐标
        var path = polygon.getPath();
        var clockwise = AMap.GeometryUtil.isClockwise(path);
        if(!clockwise){
          this.$message({
            showClose: true,
            message: '请顺时针方向绘制围栏, 警告',
            type: 'warning'
          });
          opType = "reset";
          polyEditor.setTarget();
        }else {
          var data = {"paths":path,"districtPaths":districtPolygon.getPath()}
          genQyPoints(data).then(response => {
            if(response.code==200){
            var newPaths = response.data;
            //去乡镇区域最大半径
            var radius = [];
            for(var i=1;i<newPaths.length;i++){
              var dis = AMap.GeometryUtil.distance(newPaths[0], newPaths[i]);
              dis = dis/2;
              radius.push(dis);
            }
            radius.sort();
            tempDistrict.districtRadius = radius[radius.length-1];
            map.remove(polygon);
            var polygon2 = new AMap.Polygon({
              strokeWeight: 2,
              path: newPaths,
              fillOpacity: 0.4,
              fillColor: '#199cff',
              strokeColor: '#13ffff',
              extData:{
                district: tempDistrict
              }
            });
            polyEditor.setTarget(polygon2);
            map.add(polygon2);
            polyEditor.open();
          }else{
            opType = "reset";
            polyEditor.setTarget();
            this.$message({
              showClose: true,
              message: response.msg+', 警告',
              type: 'warning'
            });
          }
        });
        }

      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.modifyName = false;
        this.isAddStatus = false;
        this.reset();
      },
      /** 重新绘制 */
      handleResetDraw(){
        if(opType!="saveCache"){
          opType = "reset";
          polyEditor.setTarget();
          polyEditor.open();
        }
      },
      // 表单重置
      reset() {
        this.form = {};
        this.assistTools = false;
        this.isEditPoint = false;
        this.isEndEdit = false;
        this.isAddStatus = false;
        this.openCopy = false;
        $(".top-input").show();
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery(isReset) {
        contextMenu.close();
        map.clearMap();
        this.getList();
        this.getDistrictList();
        if(isReset === 0){
          opType = "query";
        }
      },
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      handleOpenAdd() {
        this.reset();
        this.open = true;
        this.title = "新增区域";
        var newUserPop = [];
        this.userPopOptions.forEach(item =>{
          if(item.dictValue == this.userPop[0]){
            newUserPop.push(item)
          }else if(item.dictValue == this.userPop[1]){
            newUserPop.push(item)
          }
        })
        this.userPopOptions = newUserPop;
      },
      // 修改名称
      handleUpdateName(isConfirm){
        if(isConfirm == 1){
          this.$refs["form"].validate(valid => {
            if(valid){
              checkDistrict(this.form).then(response =>{
                if(response.data.code === 200){
                  saveQyCache(this.form).then(response =>{
                    if(response.code == 200){
                      this.msgSuccess("修改成功")
                      this.modifyName = false;
                      this.reset();
                      this.handleQuery();
                    }
                  });
                }else {
                  this.msgError(response.data.msg)
                }
              })
            }
          })
        }else {
          contextMenu.close();
          this.title = "修改区域名称"
          this.modifyName = true;
          tempDistrict = rightClickPolygon.getExtData().district;
          this.form = tempDistrict;
        }
      },
      /** 重置按钮 */
      handleReset(){
        contextMenu.close();
        contextQYMenu.close();
        tempDistrict = rightClickPolygon.getExtData().district;
        console.log(tempDistrict)
        this.$confirm('是否重置名称为' + tempDistrict.districtName + '的数据项?该操作将会重置子区域', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          if(tempDistrict.districtLevel === 3){
            return resetTownDistrict(tempDistrict);
          }else if(tempDistrict.districtLevel === 2){
            return resetDistrict(tempDistrict)
          }
        }).then(() => {
          this.handleQuery();
          this.msgSuccess("重置成功");
        })
      },
      /** 添加区域按钮操作 */
      handleAddDistrict() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            districtPolygons.forEach(item =>{
              map.remove(item);
              //获取当前选择的区域
              if(this.form.parentId == item.getExtData().districtId ){
                districtPolygon = item;
                map.add(districtPolygon);
                map.setFitView(districtPolygon);
              }
            })
            var townName;
            this.townsDistrictOptions.forEach(item =>{
              if(this.form.town == item.center){
                townName = item.name
              }
            });
            var searchAddress;
            this.localDistrictOptions.forEach(item => {
              if(this.form.parentId == item.id){
                searchAddress = item.city + item.adcodeName + townName;
              }
            });

            var paths = districtPolygon.getPath();
            paths.forEach(function(path){
                circleMarker = new AMap.CircleMarker({
                center:path,
                radius:4,//3D视图下，CircleMarker半径不要超过64px
                strokeColor:'white',
                strokeWeight:2,
                strokeOpacity:1,
                fillColor:'rgba(45,140,243,0.58)',
                fillOpacity:1,
                zIndex:10,
                bubble:true,
                cursor:'pointer',
                clickable: true
              })
              circleMarker.setMap(map)
            })

            //检查名称是否重复
            checkDistrict(this.form).then(response=>{
              if(response.data.code === 200){
                this.form.districtLevel = 3;
                map.add(districtPolygon);
                polyEditor.addAdsorbPolygons(districtPolygon);
                polyEditor.open();
                this.open = false;
                tempDistrict = this.form;
                $(".top-input").hide();
                this.isEditPoint = true;
                this.isAddStatus = true;
                this.isEndEdit = true;
                if(this.assistTools){
                  geocoder = new AMap.Geocoder()
                  geocoder.getLocation(searchAddress, function(status, result) {
                    if (status === 'complete'&&result.geocodes.length) {
                      var lanlat = result.geocodes[0].location
                      circle = new AMap.Circle({
                        center: lanlat,  // 圆心位置
                        radius: 5000, // 圆半径
                        fillColor: '#a0ffd6',   // 圆形填充颜色
                        strokeColor: '#a0ffd6', // 描边颜色
                        strokeWeight: 2, // 描边宽度
                      });
                    }
                    map.add(circle);
                    //map.setZoom(12);
                    map.setCenter([lanlat.getLng(),lanlat.getLat()]);
                    circleEditor = new AMap.CircleEditor(map, circle);
                    circleEditor.open();
                    polyEditor.close();//关闭编辑*/
                  });
                }else {
                  this.isEndEdit = false;
                  this.isEditPoint = false;
                  polyEditor.setTarget();
                  polyEditor.open();
                }
              }else{
                this.msgError(response.data.msg)
                circleMarker.setMap(null);
                this.handleQuery();
              }
            })
          }
        });
      },
      /** 复制乡镇 */
      copyTown(){
        this.title = "复制乡镇"
        this.openCopy = true;
      },
      handleCopyDistrict(){
        this.$refs["form"].validate(valid => {
          if(valid){
            var townOrDistrict;
            if(this.form.town != null){
              this.townsDistrictOptions.forEach(item =>{
                if(this.form.town === item.id){
                  townOrDistrict = item;
                }
              });
            }else {
              this.localDistrictOptions.forEach(item =>{
                if(this.form.parentId === item.id){
                  townOrDistrict = item
                }
              })
            }
            copyTownOrDistrict(townOrDistrict).then(response =>{
              this.msgSuccess("操作成功")
              this.handleQuery();
              this.reset();
            });
            this.reset();
            this.openCopy = false;
          }
        });
      },

      /** 保存按钮 */
      handleSave(){
        if(this.isEditPoint == true){
          this.$confirm('您还在编辑圆,请结束编辑再进行保存', "警告", {
            confirmButtonText: "确定",
            type: "warning"
          })
        }else {
          //this.openIsAdd = false;
          opType = "saveCache";
          polyEditor.setTarget();
        }
      },
      handleClose(){
        if(polyEditor.getTarget()){
          var polygon = polyEditor.getTarget();
          map.setFitView(
            polygon,  // 覆盖物数组
            false,  // 动画过渡到制定位置
            [60, 60, 60, 60],  // 周围边距，上、下、左、右
            14,  // 最大 zoom 级别
          );
          var district = polygon.getExtData().district;
          this.$confirm('围栏：【' + district.districtName + '】未保存，确定要放弃编辑?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() =>{
            if(this.isEndEdit != false){
              this.reset();
              this.isEdit(1);
            }
            this.isAddStatus = false;
            opType = "";
            polyEditor.setTarget();
            polyEditor.close();//关闭编辑*/
            this.handleQuery();
            $(".top-input").show();
          }).catch(() => {
              console.log("cancel");
          });
        }else{
          if(this.isEndEdit != false){
            this.reset();
            this.isEdit(1);
          }
          this.isAddStatus = false;
          polyEditor.close();//关闭编辑*/
          this.handleQuery();
          $(".top-input").show();
        }
      },
      /** 修改按钮操作,进入编辑状态 */
      handleUpdate() {
        contextMenu.close();
        this.isAddStatus = true;
        tempDistrict = rightClickPolygon.getExtData().district;
        this.$confirm('是否修改名称为' + tempDistrict.districtName + '的数据项?该操作会将子区域重置', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          opType = "";
          $(".top-input").hide();
          polyEditor.setTarget(rightClickPolygon);
          polyEditor.open();
          districtPolygons.forEach(item =>{
            if(rightClickPolygon.getExtData().district.parentId === item.getExtData().districtId){
              districtPolygon = item;
            }
          })
          var paths = districtPolygon.getPath();
          paths.forEach(function(path){
            circleMarker = new AMap.CircleMarker({
              center:[path.getLng(), path.getLat()],
              radius:4,//3D视图下，CircleMarker半径不要超过64px
              strokeColor:'white',
              strokeWeight:2,
              strokeOpacity:1,
              fillColor:'rgba(45,140,243,0.58)',
              fillOpacity:1,
              zIndex:10,
              bubble:true,
              cursor:'pointer',
              clickable: true
            })
            circleMarker.setMap(map)
          })
        })
      },
      /** 删除按钮操作 */
      handleDelete() {
        contextMenu.close();
        var district = rightClickPolygon.getExtData().district;
        this.$confirm('是否确认删除名称为' + district.districtName + '的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delDistrict(district);
        }).then(() => {
          this.handleQuery();
          this.msgSuccess("删除成功");
        })
      },
      getDistrict(value) {
        var data = {};
        data.cityCode = value;
        this.cityOptions.forEach(item => {
          if (value == item.dictValue) {
            data.city = item.dictLabel;
            this.form.city = item.dictLabel;
            this.form.cityCode = item.dictValue;
          }
        })
        getDistrictByCity(data).then(response => {
          this.districtOptions = response.data;
        })
      },
      getLocalDistrict(value){
        var data ={};
        data.adCode = value;
        data.cityCode = this.form.cityCode;
        data.districtLevel = 2;
        if(this.openCopy === true){
          data.districtPop = 0;
        }
        getLocalDistrictByCity(data).then(response=>{
          this.localDistrictOptions = response.data;
        })
      },
      /** 检测是否已被复制 */
      checkIsCopy(value){
        var data = {};
        this.townsDistrictOptions.forEach(item =>{
          if(item.id === value){
            data = item
          }
        });
        checkIsCopy(this.form).then(() =>{

        })
      },
      /** 获取本地字段 */
      getLocalTowns(value){
        var data = {};
        data.parentId = value;
        data.districtPop = 0;
        getLocalDistrictByCity(data).then(response =>{
          this.townsDistrictOptions = response.data;
          if(this.openCopy === true){
            if(this.townsDistrictOptions.length == 0){
              this.msgError("")
            }else {
              this.checkIsCopy(this.townsDistrictOptions[0].id)
            }
          }
        })
      },
      // 是否启动编辑
      isEdit(value){
        if(value == 1){
          this.isEndEdit = false;
          this.isEditPoint = false;
          map.remove(circle);
          this.handleResetDraw();
          circleEditor.close();
        }
      },
      getTowns(value){
        var data = {};
        this.localDistrictOptions.forEach(item => {
          if(value == item.id) {
            data.city = item.adcodeName;
            data.cityCode = item.adcode;
          }
        })
        getDistrictByCity(data).then(response => {
          this.townsDistrictOptions = response.data;
        })
      }
    }
  };
</script>
